package com.dc.service.impl;

import com.dc.base.exception.BusinessException;
import com.dc.base.exception.ResponseCode;
import com.dc.base.pojo.BaseModel;
import com.dc.mapper.SysRoleDao;
import com.dc.pojo.SysRole;
import com.dc.pojo.SysRolePermission;
import com.dc.service.SysRoleService;
import com.dc.vo.SysRoleVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.ws.Response;
import java.util.Iterator;
import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired private SysRoleDao roleDao;
    public BaseModel selectRoleAll(BaseModel baseModel, String likeName) {
        List<SysRole> roles =roleDao.selectRoleAll(likeName);
        baseModel.setResultCode(0);
        baseModel.setMessage("角色列表查询成功！");
        baseModel.setData(roles);
        return baseModel;
    }

    public BaseModel selectRoleAll(BaseModel baseModel,int page,int size){
        PageHelper.startPage(page,size);
        List<SysRole> roleList = roleDao.selectRoleAll(null);
        PageInfo pageInfo = new PageInfo(roleList);
        baseModel.setResultCode(ResponseCode.PAGE_SUCCESS.getCode());
        baseModel.setMessage(ResponseCode.PAGE_SUCCESS.getMessage());
        baseModel.setData(pageInfo);
        return baseModel;
    }

    public BaseModel insertRole(SysRoleVo sysRoleVo, BaseModel baseModel) {
        SysRole sysRole = roleDao.selectByNameRole(sysRoleVo.getRole().getName());
        if(sysRole==null){
            int count = roleDao.insertRole(sysRoleVo.getRole());
            if(count == 0){
                throw new BusinessException("新增角色失败，SQL语句出现异常");
            }

            Iterator i = sysRoleVo.getListRolePermission().iterator();

            while(i.hasNext()) {
                SysRolePermission permission = (SysRolePermission)i.next();
                permission.setFk_role_id(sysRoleVo.getRole().getRole_id());
                permission.setCreate_user_id(sysRoleVo.getRole().getCreate_user_id());
                permission.setCreate_user_name(sysRoleVo.getRole().getCreate_user_name());
                if (permission.getPermission_value().indexOf("1") > -1) {
                    permission.setPermission_value(permission.getPermission_value().replace(",", ""));
                    this.roleDao.insertRolePermission(permission);
                }
            }
        }else{
            throw new BusinessException(ResponseCode.ROLE_ERROR.getCode(),ResponseCode.ROLE_ERROR.getMessage());
        }
        return null;
    }
}
